// ----------------
// import common api
// ----------------
import org.pi.common.Api._
import org.pi.common.geom._

// ----------------
// load input image
// ----------------
var im = rgb2gray(imread("data/abstrakt.png"))
im = hanningBlur(im,5) // blur image

// ----------------
// compute gradient and binary edge image
// ----------------
val (ix, iy) = gradient(im)
val absGrad = abs(ix,iy)
val edge = (absGrad > max(absGrad)*0.5f)

// ----------------
// compute hough akkumulator
// ----------------
val angleResolution = 100 // parameteer
val radiusResolution = 100 // parameteer
val akku = zeros(radiusResolution, angleResolution)
val h = im.length(0)
val w = im.length(1)
val maxRadius = Point(w,h).length / 2.0f

// draw a sine into the akkumulator 
// (compare Hough Transform; Folien Teil 5: r = x cosa + y sina)
def drawSine(x: Float, y:Float): Unit = {
	var angleIndex=0
	while(angleIndex<radiusResolution) {
        // convert angleIndex to real angle
        val angle = angleIndex.toFloat * pi / radiusResolution.toFloat
        // compute radius form angle and location (x,y)
        val radius = x*Math.cos(angle)+ y*Math.sin(angle)
        // check if radius is valid (within akkumulator)
        if (radius>=(-maxRadius) && radius<=maxRadius) {
            // convert real radius to radiusIndex
	        val radiusIndex = ((radius+maxRadius) * radiusResolution.toFloat / (2.0f*maxRadius)).toInt
	        // modify akkumulator at location radiusIndex, angleIndex
	        // the pixel (x,y) is responsible for this sine.
	        akku(radiusIndex, angleIndex) += 1.0f
        }        
        angleIndex+=1
    }
}

// process all pixels and call "drawSine"
var x=0
while(x<w) {
    var y=0
    while(y<h) {
        if (edge(y,x)) drawSine(x.toFloat - w.toFloat/2.0f,y.toFloat - h.toFloat/2.0f)
        y+=1
    }
    x+=1
}

// ----------------
// output
// ----------------
figure
// show output image
subplot(2,2,0);
imshow( -absGrad )

subplot(2,2,1);
imshow( !edge )

subplot(2,2,2);
imshow( -akku )

// connect subplot 0 and 1 (--> synchroneous zoom)
gcf.getAxesForSubplot(2,2,0) connectToAxes gcf.getAxesForSubplot(2,2,1)



